<?php

namespace App\HttpController\XApp\Qr\Admin;


use App\Common\Log;
use App\Common\OA\OA;
use App\Common\WX\Api\OfficialAccount;
use App\HttpController\ControllerAdmin;
use App\Model\t_s_app;
use App\Model\t_wx_qr;
use App\Model\t_wx_reply;
use XWX\Common\H;
use XWX\Common\Validate\Validate;

class QrEdit extends ControllerAdmin
{
    public function edit()
    {
        $this->funcSetTitle("二维码-编辑");


        $data = [];
        if ($this->funcIsAdminEdit())
        {
            $entity = t_wx_qr::funcLoad($this->db(), $this->getID());

            $entity_reply = t_wx_reply::funcLoad($this->db(), $entity->wxqr_reply_id);


            $data_append = [
                'id' => $entity->funcGetID(),
                'qr_url' => $entity->getQrUrl(),
                'reply_name' => $entity_reply->reply_name,
            ];
            $data = array_merge($entity->toArray(), $data_append);
        }


        $this->commonR()->setData('data', $data);
        $this->funcWriteCommonR();
    }

    public function save()
    {
        $v = new Validate();
        $v->addColumn('wxqr_name')
            ->required()
            ->lenMax(50);
        $v->addColumn('wxqr_reply_id')
            ->required();


        if (!$v->validate($this->reqParam(), true))
        {
            return $this->funcWriteValidate($v->getErrors());
        }


        $ignore_field = [];
        if ($this->funcIsAdminEdit())
        {
            $ignore_field = ['wxqr_type', 'wxqr_type_qr'];
        }


        $this->funcSave(t_wx_qr::class, $ignore_field, false);


        $this->funcWriteCommonR();
    }


    public function funcSaveBefore($entity)
    {
        if ($this->funcIsAdminAdd())
        {
            $type = '';
            if ($this->funcGetX__config()->aconfig_type == "wxapp")
            {
                $type = "wxapp";
            }

            $entity->wxqr_type = $type;
            $entity->wxqr_type_qr = "QR_LIMIT_SCENE";


            Log::funcLogDebug(__METHOD__, "生成二维码");
            $app = OfficialAccount::funcIns($this->funcGetX__config());
            $r = $app->funcQrCreate($entity->wxqr_reply_id);
            if ($r->err())
            {
                throw new \Exception($r->errmsg);
            }

            $ticket = $r->getData('ticket');
            $entity->wxqr_info = $ticket;
        }

        Log::funcLog(__METHOD__, $entity->toArray());
    }
}